/**
 * @file webpack 的任务配置，包括 webpack 的本地测试和打包上线
 *
 * @author liubin29@baidu.com
 * 2015年10月27日
 */


var util = require('../lib/util');
var config = require('./');
var webpack = require('webpack');
var WebpackManifest = require('../lib/webpackManifest');

var publicPath = '/js/';

module.exports = function (env) {
    var jsDest = config.publicDirectory + '/js/';

    var timestamp = util.formatDate(new Date(), 'yyyyMMddhhmm');
    var webpackConfig = {
        context: config.sourceDirectory,
        entry: {
            'main': config.sourceDirectory + '/main.js'
        },
        output: {
            path: jsDest,
            publicPath: './js/',
            filename: env === 'production' ? '[name]-' + timestamp + '.js' : '[name].js'
            // filename: env === 'production' ? '[name]-[hash].js' : '[name].js'
        },
        plugins: [],
        resolve: {
            extensions: ['.js', '.vue'],
            modules: [
                config.sourceDirectory, 'node_modules', 'node_modules/mip/src', 'node_modules/mip/deps'
            ],
            alias: {
                // 'vue': 'vue/dist/vue.js',
                util: 'util.js',
                'im-lib': config.sourceDirectory + '/common/dep/im-core/dep/im-lib/0.1.0/src/pc/',
                'etpl': config.sourceDirectory + '/common/dep/etpl/src/',
                'im-core': config.sourceDirectory + '/common/dep/im-core/src/',
                'im-filter': config.sourceDirectory + '/common/dep/im-filter/0.1.0/src/',
                'b-link-core': config.sourceDirectory + '/common/dep/im-core/dep/b-link-js-sdk/src/Core',
                'jquery-cookie': config.sourceDirectory + '/common/dep/im-core/dep/jquery-cookie/jquery.cookie.js',
            },
            mainFiles: ['index', 'main']
        },
        module: {
            loaders: [{
                    test: /\.vue$/,
                    loader: 'vue-loader'
                },
                // {test: function (filePath) {
                //     let compPath = config.sourceDirectory + '/components/';
                //     if (filePath.indexOf(compPath) === 0 && /index\.vue$/.test(filePath)) {
                //         return true;
                //     }
                //     return false;
                // }, loader: 'leo-vue-loader'},
                {
                    test: /\.js$/,
                    loader: 'babel-loader',
                    query: {
                        presets: ['es2015'],
                        plugins: ['transform-runtime']
                    },
                    exclude: /node_modules/
                },
                {
                    test: /\.styl$/,
                    loader: 'stylus-loader'
                },
                {
                    test: /\.css$/,
                    loader: 'style-loader!css-loader'
                },
                {
                    test: /\.json$/,
                    loader: 'json-loader'
                },
                {
                    test: /\.html$/,
                    loader: 'html-loader'
                },
                {
                    test: /\.less$/,
                    loader: 'style-loader!css-loader!less-loader',
                    exclude: /node_modules/
                },
                {
                    test: /\.less.us$/,
                    loader: 'css-loader!less-loader',
                    exclude: /node_modules/
                },
                {
                    test: /\.(png|jpg|gif|ico)/,
                    loader: 'file-loader?name=[path][name].[ext]'
                },
                {
                    test: /\.(ttf|woff|woff2|eot|svg)/,
                    loader: 'file-loader?name=[path][name].[ext]'
                }
            ]
        }
    };

    // webpackConfig.plugins.push(new webpack.ProvidePlugin({
    //     '$': 'jquery',
    //     'jQuery': 'jquery',
    //     'window.jQuery': 'jquery'
    // }));

    var conf = env === 'development' ? require('./webpack.dev') : require('./webpack.prod');

    if (env === 'development') {
        webpack.debug = true;
        webpackConfig.devtool = 'sourcemap';
    }

    var formatDate = function (date, fmt) {
        var o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(), // 日
            'h+': date.getHours(), // 小时
            'm+': date.getMinutes(), // 分
            's+': date.getSeconds(), // 秒
            'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
            'S': date.getMilliseconds() // 毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
                fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
            }
        }
        return fmt;
    };

    var strReplace = 'http://ipangu.baidu.com/$1/';
    if (process.env.NODE_ENV === 'test') {
        strReplace = 'http://ipangu-test.baidu.com/$1/';
    }
    var replaceLoader = {
        test: /\.js$/,
        loader: 'string-replace-loader',
        query: {
            multiple: [{
                search: '$buildTime$',
                replace: formatDate(new Date(), 'yyyymmddHHMMss')
            }, {
                search: '$date$',
                replace: formatDate(new Date(), 'yyyymmdd')
            }, {
                search: '$blinkServerEmi$',
                replace: '10.36.176.18:8561'
            }, {
                search: '$blinkServerRainbow$',
                replace: 'blinkServerRainbowQA'
            }, {
                search: '$ucLoginSDK$',
                replace: 'qa-'
            }]
        }
    };
    webpackConfig.module.loaders.push(replaceLoader);

    if (env === 'production') {
        webpackConfig.plugins.push(
            new WebpackManifest(publicPath, config.distPath + '/' + config.basePath),
            new webpack.DefinePlugin({
                'process.env': {
                    NODE_ENV: JSON.stringify('production')
                }
            })
        );
    }

    webpackConfig.plugins.push(new webpack.DefinePlugin({
        INJECT_ROUTER: JSON.stringify(conf.router)
    }));

    return webpackConfig;
};